// mycomponent/Waterfalls_flow.js
var location = require("../../mybehaviors/location/location");
var app = getApp();
Page({
  behaviors: [location],
  options: {
    styleIsolation: 'shared',
  },
  data:{
    stickid:'',
    showActionSheet: false,
    ActionSheetOptions:[
      {'name':'上传图片','disabled':false},
      {'name':'上传视频','disabled':false}
    ],
    goods_open: null,
    uploadNumber:10,
    photosize: 1024 * 1024 * 4, // 图片大小限制
    uploadUrl: 'upload.uploadPic',
    releasetitle:'',
    releasecontents:'',
    imgData: [],
    catelist: [],
    selectCateList: [],
    showTopicBox: false,
    showTopicPopup: false,
    goodsArr:[],
    groupChatArr:[],
    addressText:'北京市朝阳区东湖渠华彩大厦',
    dataJson:{
      "resource_type":1,
      "cat_id":'',
      "contents":"",
      "address":"",
      "images":[],
      "title":"",
      "goods_id":'',
      "store_id":"",
      "city":"",
      "lat":'',
      "lng":'',
      "audio":[],
      "video":{
        'url':'',
        'image':''
      },
      "chat_group_id":'',
      "chat_group_image":'',
      "chat_group_name":''
    },
    titleNumber:0,
    videoPoster:'',
    chatJsonData: null,
    storageData:{
      updateType:'',
      images:[],
      video:'',
      videoPoster:'',
      title:'',
      miaoshu:'',
      huatileixing:[],
      goods:[],
      chat:null
    }
  },
  titleChange(e){
    console.log(e)
    this.setData({
      titleNumber: e.detail.length,
      'storageData.title':e.detail
    })
    this.data.dataJson.title = e.detail
    wx.setStorageSync('storageData',this.data.storageData)
  },
  describeChange(e){
    this.setData({
      titleNumber: e.detail.length,
      'storageData.miaoshu':e.detail
    })
    this.data.dataJson.contents = e.detail
    wx.setStorageSync('storageData',this.data.storageData)
  },
  cancelreleasePost(){
    wx.navigateBack({
      delta: 1
    })
  },
  releasePost(){
    if(this.data.dataJson.images.length == 0 && this.data.dataJson.resource_type == 1){
      wx.showToast({
        icon: 'none',
        title: '请上传图片或者视频',
        duration: 1500
      });
      return false
    }
    if(this.data.dataJson.resource_type == 2 && !this.data.dataJson.video.url){
      wx.showToast({
        icon: 'none',
        title: '请上传视频',
        duration: 1500
      });
      return false
    }
    if(this.data.dataJson.resource_type == 2 && this.data.dataJson.video.url && !this.data.dataJson.video.image){
      wx.showToast({
        icon: 'none',
        title: '请上传封面',
        duration: 1500
      });
      return false
    }
    if(this.data.dataJson.title == ''){
      wx.showToast({
        icon: 'none',
        title: '请填写标题',
        duration: 1500
      });
      return false
    }
    if(this.data.dataJson.contents == ''){
      wx.showToast({
        icon: 'none',
        title: '请填写描述',
        duration: 1500
      });
      return false
    }
    if(this.data.selectCateList.length == 0){
      wx.showToast({
        icon: 'none',
        title: '请选择话题',
        duration: 1500
      });
      return false
    }
    let selectCateID = [];
    this.data.selectCateList.forEach((item)=>{
      selectCateID.push(item.id)
    })
    let cateIDstr = selectCateID.join(',');
    this.data.dataJson.cat_id = cateIDstr
    let selectGoodsID = [];
    this.data.goodsArr.forEach((item)=>{
      selectGoodsID.push(item.id)
    })
    let selectGoodsIDstr = selectGoodsID.join(',')
    this.data.dataJson.goods_id = selectGoodsIDstr
    let urlStr = app.getNetAddresss("plugin.micro-communities.api.trick.publish");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: this.data.dataJson,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
          wx.navigateBack({
            delta: 1
          })
          wx.setStorageSync('storageData', '')
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        clickTap = 0;
      }
    });
  },
  addressClick(){
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const url = `/${currentPage.route}?page_id=${this.data.page_id}`;
    wx.setStorageSync('diyurl', url);
    wx.navigateTo({
      url: '/packageC/o2o/o2oLocation/o2oLocation?tag=goback'
    });
  },
  linkAssociationGroupChat(){
    if(this.data.chatJsonData){
      wx.setStorageSync('groupChatJson', this.data.chatJsonData)
    }
    wx.navigateTo({
      url: '/TUI-CustomerService/pages/index?GLchat=GLchat'
    });
  },
  onLoad(){
    this.getAgreement()
  },
  onReady(){
    
  },
  onShow(){
    const goods = wx.getStorageSync('PostGoods')
    const chatJson =  wx.getStorageSync('groupChatJson')
    if(goods){
      this.setData({
        goodsArr:goods,
        'storageData.goods':goods
      })
      wx.setStorageSync('storageData',this.data.storageData)
      wx.setStorageSync('PostGoods', '')
    }
    if(chatJson){
      this.setData({
        'storageData.chat':chatJson,
        chatJsonData:chatJson,
        'dataJson.chat_group_id':chatJson.id,
        'dataJson.chat_group_name':chatJson.name,
        'dataJson.chat_group_image':'https://web.sdk.qcloud.com/component/TUIKit/assets/avatar_21.png'
      })
      wx.setStorageSync('storageData',this.data.storageData)
      wx.setStorageSync('groupChatJson', '')
    }
    const storageData =  wx.getStorageSync('storageData')
    if(storageData){
      if(storageData.updateType){
        if(storageData.updateType == 1){
          this.data.ActionSheetOptions[1].disabled = true
        } else {
          this.data.ActionSheetOptions[0].disabled = true
        }
        this.setData({
          'storageData.updateType':storageData.updateType,
          ActionSheetOptions:this.data.ActionSheetOptions
        })
      }
      if(storageData.images && storageData.images.length != 0){
        this.setData({
          'storageData.images':storageData.images,
          'dataJson.images':storageData.images
        })
      }
      if(storageData.video){
        this.setData({
          'storageData.video':storageData.video,
          'dataJson.video.url':storageData.video
        })
      }
      if(storageData.videoPoster){
        this.setData({
          'storageData.videoPoster':storageData.videoPoster,
          'dataJson.video.image':storageData.videoPoster
        })
      }
      if(storageData.title){
        this.setData({
          titleNumber: storageData.title.length,
          'storageData.title':storageData.title,
          'dataJson.title':storageData.title
        })
      }
      if(storageData.miaoshu){
        this.setData({
          'storageData.miaoshu':storageData.miaoshu,
          'dataJson.contents':storageData.miaoshu
        })
      }
      if(storageData.huatileixing && storageData.huatileixing.length != 0){
        this.setData({
          'storageData.huatileixing':storageData.huatileixing,
          selectCateList:storageData.huatileixing
        })
      }
      if(storageData.goods && storageData.goods.length != 0){
        this.setData({
          'storageData.goods':storageData.goods,
          goodsArr:storageData.goods
        })
      }
      if(storageData.chat){
        this.setData({
          'storageData.chat':storageData.chat,
          chatJsonData:storageData.chat,
          'dataJson.chat_group_id':storageData.chat.id,
          'dataJson.chat_group_name':storageData.chat.name,
          'dataJson.chat_group_image':'https://web.sdk.qcloud.com/component/TUIKit/assets/avatar_21.png'
        })
      }
    }
    this._getLocation((mapdata,e)=>{
      console.log(mapdata,'---------')
      this.setData({
        'dataJson.address': mapdata.address,
        'dataJson.city': mapdata.address_component.city ? mapdata.address_component.city : mapdata.address_component.province,
        'dataJson.lat': mapdata.location.lat,
        'dataJson.lng': mapdata.location.lng
      });
    });
  },
  onHide(){

  },
  onUnload(){

  },
  onPullDownRefresh(){

  },
  onReachBottom(){

  },
  onShareAppMessage(){
    
  },
  deleteChat(){
    this.setData({
      chatJsonData:null,
      'dataJson.chat_group_id':'',
      'dataJson.chat_group_name':'',
      'dataJson.chat_group_image':'',
      'storageData.chat':null
    })
    wx.setStorageSync('storageData',this.data.storageData)
  },
  //判断是否为达人
  getAgreement() {
    let urlStr = app.getNetAddresss("plugin.micro-communities.api.trick.getAgreement");
    app._getNetWork({
      url: urlStr,
      data: {
        validate_page: 1
      }, // validate_page 实名认证判断
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            goods_open: (res.data ? res.data.goods_open : 0)
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  deletePictFn(e){
    console.log(e)
    let deleteItemIndex = e.currentTarget.dataset.index
    this.data.dataJson.images.splice(deleteItemIndex,1)
    this.setData({
      'dataJson.images':this.data.dataJson.images,
      'storageData.images':this.data.dataJson.images
    })
    if(this.data.dataJson.images.length == 0){
      this.setData({
        ActionSheetOptions:[
          {'name':'上传图片','disabled':false},
          {'name':'上传视频','disabled':false}
        ],
        'storageData.updateType':''
      })
    }
    wx.setStorageSync('storageData',this.data.storageData)
  },
  deleteVideoPosterFn(){
    this.setData({
      'dataJson.video.image':'',
      'storageData.videoPoster':''
    })
    if(!this.data.dataJson.video.url){
      this.setData({
        'dataJson.resource_type':1,
        'storageData.updateType':''
      })
    }
    wx.setStorageSync('storageData',this.data.storageData)
  },
  deleteVideoFn(){
    this.setData({
      ActionSheetOptions:[
        {'name':'上传图片','disabled':false},
        {'name':'上传视频','disabled':false}
      ],
      'dataJson.video.url':'',
      'storageData.video':'',
      'storageData.updateType':''
    })
    wx.setStorageSync('storageData',this.data.storageData)
  },
  selectTopic() {
    this.setData({
      showTopicPopup: true
    });
    this.getClassificationData();
  },
  onCloseTopicPopup(){
    this.setData({
      showTopicPopup: false
    });
  },
  getClassificationData() {
    let that = this;
    let json = {};
    let urlStr = app.getNetAddresss("plugin.micro-communities.api.index.getCate");
    if (this.data.commodityTitle) {
      json.cName = this.data.commodityTitle;
    }
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          res.data.data.forEach((item)=>{
            item['selectTopicId'] = false
          })
          if(that.data.selectCateList.length != 0){
            that.data.selectCateList.forEach((item)=>{
              res.data.data.forEach((ite)=>{
                if(item.id == ite.id){
                  ite.selectTopicId = true
                }
              })
            })
          }
          that.setData({
            catelist: res.data.data
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  confirmSelectTopic(){
    this.setData({
      selectCateList: []
    })
    this.data.catelist.forEach((item,index)=>{
      if(item.selectTopicId){
        this.data.selectCateList.push(item)
      }
    })
    this.setData({
      selectCateList: this.data.selectCateList,
      'storageData.huatileixing': this.data.selectCateList
    });
    wx.setStorageSync('storageData',this.data.storageData)
    this.setData({
      showTopicPopup: false
    });
  },
  selectTopicFn(e){
    let clickItemIndex = e.currentTarget.dataset.index
    let number = 0
    this.data.catelist.forEach((item,index)=>{
      if(item.selectTopicId){
        number +=1
      }
    })
    if(number == 3 && !this.data.catelist[clickItemIndex].selectTopicId){
      wx.showToast({
        icon: 'none',
        title: '最多关联3个分类'
      })
      return false
    }
    this.data.catelist.forEach((item,index)=>{
      if(index === clickItemIndex){
        if(item.selectTopicId){
          item.selectTopicId = false
        } else {
          item.selectTopicId = true
        }
      }
    })
    this.setData({
      catelist: this.data.catelist
    });
  },
  onCloseActionSheet(){
    this.setData({
      showActionSheet:false
    })
  },
  onSelectActionSheet(e){
    console.log(e.detail)
    if(e.detail.name === '上传图片'){
      if(this.data.dataJson.video.image){
        wx.showToast({
          icon:'none',
          title: '请先删除封面图'
        })
        return false
      }
      let that = this;
      let number = that.data.uploadNumber - that.data.dataJson.images.length;
      let urlStr = app.getNetAddresss(this.data.uploadUrl);
      wx.chooseImage({
        count: number,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success(res) {
          const tempFilePaths = res.tempFilePaths;
          console.log(res);
          for (let j = 0; j < tempFilePaths.length; j++) {
            wx.compressImage({
              src: tempFilePaths[j], // 图片路径
              quality: 60, // 压缩质量
              success(e) {
                console.log(e);
                let photourl = e.tempFilePath;
                wx.uploadFile({
                  url: urlStr,
                  filePath: photourl,
                  name: 'file',
                  success(resdata) {
                    let res = JSON.parse(resdata.data);
                    if (res.result == 1) {
                      let imageUrl1 = res.data.img_url;
                      let imgData = that.data.dataJson.images;
                      imgData.push(imageUrl1);
                      that.setData({
                        'dataJson.images': imgData,
                        'dataJson.resource_type': 1,
                        'storageData.updateType':1,
                        'storageData.images':imgData
                      });
                      that.data.ActionSheetOptions[1].disabled = true
                      that.setData({
                        showActionSheet: false,
                        ActionSheetOptions:that.data.ActionSheetOptions
                      })
                      wx.setStorageSync('storageData', that.data.storageData)
                    } else {
                      wx.showToast({
                        icon: 'none',
                        title: res.msg,
                        duration: 1500
                      });
                    }
                  }
                });
              },
              fail(e) {},
              complete(e) {}
            });
          }
        }
      });
    } else if (e.detail.name === '上传视频') {
      let that = this;
      let urlStr = app.getNetAddresss(this.data.uploadUrl);
      wx.chooseVideo({
        sourceType: ['album','camera'],
        compressed:true,
        maxDuration: 60,
        camera: 'back',
        success(res) {
          console.log(res,'--------------video')
          if(res.duration>300){
            wx.showToast({
              icon: 'none',
              title: '请选择时长小于5分钟的视屏',
            })
            return false
          }
          wx.compressVideo({
            src: res.tempFilePath, // 视频路径
            quality: 'medium', // 压缩质量
            success(e) {
              console.log(e,'------yasuohoude')
              let photourl = e.tempFilePath
              // let photourl = res.tempFilePath
              wx.showLoading({
                mask:true,
                title: '上传中',
              })
              wx.uploadFile({
                url: urlStr,
                filePath: photourl,
                name: 'file',
                success(resdata) {
                  console.log(resdata,'---------resdata')
                  let res = JSON.parse(resdata.data);
                  wx.hideLoading()
                  if (res.result == 1) {
                    wx.showToast({
                      icon: 'none',
                      title: '上传成功',
                      duration: 1500
                    });
                    console.log(res,'-----------videourl')
                    that.data.ActionSheetOptions[0].disabled = true
                    that.setData({
                      'dataJson.video.url': res.data.img_url,
                      'dataJson.resource_type': 2,
                      'storageData.updateType': 2,
                      'storageData.video':res.data.img_url,
                      showActionSheet: false,
                      ActionSheetOptions:that.data.ActionSheetOptions
                    })
                    wx.setStorageSync('storageData', that.data.storageData)
                  } else {
                    wx.showToast({
                      icon: 'none',
                      title: res.msg,
                      duration: 1500
                    });
                  }
                }
              });
            },
            fail(e){
              console.log(e)
            }
          })
        }
      })
    }
  },
  upPicturePoster(){
    let that = this;
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        console.log(res);
        for (let j = 0; j < tempFilePaths.length; j++) {
          wx.compressImage({
            src: tempFilePaths[j], // 图片路径
            quality: 60, // 压缩质量
            success(e) {
              console.log(e);
              let photourl = e.tempFilePath;
              wx.uploadFile({
                url: urlStr,
                filePath: photourl,
                name: 'file',
                success(resdata) {
                  let res = JSON.parse(resdata.data);
                  if (res.result == 1) {
                    let imageUrl1 = res.data.img_url;
                    that.setData({
                      'dataJson.video.image': imageUrl1,
                      'storageData.videoPoster': imageUrl1
                    });
                  } else {
                    wx.showToast({
                      icon: 'none',
                      title: res.msg,
                      duration: 1500
                    });
                  }
                }
              });
            },
            fail(e) {},
            complete(e) {}
          });
        }
      }
    });
  },
  upPicture() {
    this.setData({
      showActionSheet:true
    })
  },
  linkAssociationGoods(){
    let goodsIDs = [];
    this.data.goodsArr.forEach((item)=>{
      goodsIDs.push(item.id)
    })
    let idsstr = goodsIDs.join(',')
    wx.navigateTo({
      url: "/packageLYQ/associationGoods/associationGoods?ids="+idsstr,
    });
  }
})
